package com.xlx.openLink.template;

import com.xlx.openLink.base.BaseMessage;
import com.xlx.openLink.base.ThreadRunTimeExcption;
import com.xlx.openLink.enums.ResultCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

@Component
public class OpenLinkTemplate {

    @Autowired
    TransactionTemplate transactionTemplate;

    private static final Logger LOGGER = LoggerFactory.getLogger(OpenLinkTemplate.class);

    public void execute(final OpenTemplateCallBack callBack, BaseMessage msg, Boolean withTransaction) {
        try {
            callBack.doCheck();
            if (withTransaction) {
                transactionTemplate.execute(x -> {
                    callBack.doExecute();
                    return null;
                });
            } else {
                callBack.doExecute();
            }
        } catch (ThreadRunTimeExcption e) {
            LOGGER.error("功能异常", e);
            msg.buildFail(e.getResultCodeEnum());
        } catch (DataAccessException e) {
            LOGGER.error("数据库异常", e);
            msg.buildFail(ResultCodeEnum.DATA_ACCESS_EXCEPTION);
        } catch (Exception e) {
            LOGGER.error("系统异常", e);
            msg.buildFail(ResultCodeEnum.SERVER_ERROR);
        }
    }


}
